package com.nuctech.hardwaredriver.serialport_library.core.codec;

import com.nuctech.hardwaredriver.serialport_library.bean.ReadSerialPortDataBean;
import com.nuctech.hardwaredriver.serialport_library.core.exception.SerialPortException;
import com.nuctech.hardwaredriver.util.DefaultConfigUtil;

/**
 * Created by 心魂free on 2019/11/7.
 * <p>
 * 默认的数据处理类
 */

public class DefaultHandler implements SerialPortHandler {

    private ReceiveSerialPortDataCallback mReceiveSerialPortDataCallback;

    public DefaultHandler(ReceiveSerialPortDataCallback receiveSerialPortDataCallback) {

        this.mReceiveSerialPortDataCallback = receiveSerialPortDataCallback;
    }

    @Override
    public void messageReceived(byte[] receiverData) {

        ReadSerialPortDataBean<byte[]> readSerialPortDataBean = null;
        if (receiverData != null) {

            //解析数据后传递给业务层
            readSerialPortDataBean = new ReadSerialPortDataBean<>();
            //检查首字节是否正确
            int firstData = receiverData[0] & 0xff;
            switch (firstData) {

                case DefaultConfigUtil.SINGLERESULTDATA: {

                    readSerialPortDataBean.setSuccess(true);
                }
                break;

                case DefaultConfigUtil.MULTITUDINOUSRESULTHEADDATA: {

                    //检查尾字节是否正确
                    int footData = receiverData[receiverData.length - 1] & 0xff;
                    if (footData == DefaultConfigUtil.MULTITUDINOUSRESULTFOOTDATA) {

                        readSerialPortDataBean.setSuccess(true);
                        byte[] resultData = new byte[receiverData.length - 2];
                        System.arraycopy(receiverData, 1, resultData, 0, resultData.length);
                        readSerialPortDataBean.setT(resultData);

                    } else {

                        readSerialPortDataBean.setSuccess(false);
                    }
                }
                break;

                default: {

                    readSerialPortDataBean.setSuccess(false);
                }
                break;
            }
        }

        if (mReceiveSerialPortDataCallback != null) {

            mReceiveSerialPortDataCallback.onDataReceived(readSerialPortDataBean);

        } else {

            throw new SerialPortException("ReceiveSerialPortDataCallback函数为null");
        }
    }
}
